/*
 * @Author: sansuixiaoxianxian 1634119605@qq.com
 * @Date: 2025-07-10 11:09:27
 * @LastEditors: sansuixiaoxianxian 1634119605@qq.com
 * @LastEditTime: 2025-07-11 12:09:47
 * @FilePath: /travel-record-library/src/pages/SystemDataManagement/exportDataUtil.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {
	DB,
	lumpSumCarFareLibraryKey,
	travelAddressLibraryKey,
	travelPeopleLibraryKey,
	travelRecordLibraryKey,
} from "@/assets/global"
import * as indexedDB from "@utility/indexedDB"

import { TTravelInfo } from "../AddTravelRecord/AddTravelRecord"
import _ from "lodash"
import SystemDataManagementClass, {
	DOWNLOAD_PATH,
} from "./SystemDataManagement"
import dayjs from "dayjs"
import { showFailToast, showToast } from "vant"
import { FileExporter } from "@/utility/fileUtils"
import TravelRecordLibraryStore from "@/store/TravelRecordLibraryStore"
const store = TravelRecordLibraryStore()

const exportDataUtil = async (
	main: SystemDataManagementClass
): Promise<string> => {
	try {
		// 1. 校验输入
		if (main.selectProject.length === 0) {
			showToast("请选择导出项目。")
			return ""
		}

		// 2. 定义数据处理器（避免重复代码）
		const handlers: Record<string, () => Promise<any> | any> = {
			[travelRecordLibraryKey]: async () => {
				const result = (await indexedDB.queryAll(
					DB.store.TravelRecord.name
				)) as TTravelInfo[]
				return exportTravelInfos(result)
			},
			[travelPeopleLibraryKey]: () => _.cloneDeep(store.PeopleLibrary),
			[travelAddressLibraryKey]: () => _.cloneDeep(store.AddressLibrary),
			[lumpSumCarFareLibraryKey]: () =>
				_.cloneDeep(store.LumpSumCarFareLibrary),
		}

		// 3. 并行执行所有导出操作（提升性能）
		const results = await Promise.all(
			main.selectProject.map(async (item: string | number) => {
				const handler = handlers[item]
				if (!handler) return null // 忽略无效项
				return [item, await handler()] as const
			})
		)

		// 4. 过滤无效结果并生成 Map
		const arr = results.filter(Boolean) as [string, any][]
		const resultMap = new Map(arr)

		// 5. 导出文件
		const filename = `（${dayjs().format(
			"YYYYMMDD"
		)}）差旅系统数据库`
		FileExporter.exportTXT(JSON.stringify(Object.fromEntries(resultMap)), {
			filename,
		})


		// 6. 处理 Hybrid App 下载路径
		if (window.plus) {
			return `${DOWNLOAD_PATH}${filename}`
		}
		main.selectProject = []
		return ""
	} catch (error) {
		console.error("导出失败:", error)
		showFailToast("导出失败，请检查数据或重试。")
		return ""
	}
}

export const exportTravelInfos = (data: TTravelInfo[]) => {
	return data.map(item => ({
		...item,
		travelDate: item.travelDate.replace(/-/g, "/"),
		createDate: item.createDate.replace(/-/g, "/"),
		travelPeople: Array.from(item.travelPeople),
	}))
}

export default exportDataUtil
